package com.sky.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    private DishFlavorService dishFlavorService;
    private SetmealDishService setmealDishService;
    private DishMapper dishMapper;

    public DishServiceImpl(DishFlavorService dishFlavorService, SetmealDishService setmealDishService, DishMapper dishMapper) {
        this.dishFlavorService = dishFlavorService;
        this.setmealDishService = setmealDishService;
        this.dishMapper = dishMapper;
    }


    /**
     * 新增菜品和对应的口味
     *
     * @param dishDTO 实体类
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

//        向菜品表插入1条数据
        this.save(dish);

//        赋值外键ID
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));

//        向口味表插入n条数据
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public IPage<DishVO> pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!("".equals(dishPageQueryDTO.getName()) || dishPageQueryDTO.getName() == null), Dish::getName, dishPageQueryDTO.getName())
                .eq(dishPageQueryDTO.getCategoryId() != null, Dish::getCategoryId, dishPageQueryDTO.getCategoryId())
                .eq(dishPageQueryDTO.getStatus() != null, Dish::getStatus, dishPageQueryDTO.getStatus())
                .orderByDesc(Dish::getCreateTime);


        IPage<DishVO> iPage = new Page<>(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        return this.baseMapper.pageQuery(iPage, wrapper);
    }

    /**
     * 菜品批量删除
     *
     * @param ids 被删除的条件id
     */
    @Override
    @Transactional
    public void delByIds(List<Long> ids) {
//        判断当前菜品是否能够删除
        for (Long id : ids) {

            //        是否存在起售中的菜品？
            if (this.baseMapper.selectById(id).getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            //        是否被套餐关联?
            LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SetmealDish::getSetmealId, id);

            if (!setmealDishService.list(wrapper).isEmpty()) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }

            //        删除菜品表中的菜品数据
            this.removeById(id);
            //        删除菜品相关的口味数据
            dishFlavorService.removeById(id);
        }
    }

    /**
     * 根据id查询菜品和对应的口味数据
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
//        根据id查询口味数据
        Dish dish = this.getById(id);

//        根据菜品id查询口味数据
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, id);

        List<DishFlavor> dishFlavors = dishFlavorService.list(wrapper);

//        将查询道德数据封装到VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

//        修改菜品表基本信息
        this.baseMapper.updateById(dish);

//        删除原有的口味数据
        dishFlavorService.getBaseMapper().deleteById(dishDTO.getId());

//        重新插入口味数据(赋值外键ID)
        List<DishFlavor> flavors = dishDTO.getFlavors();

        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));

//        向口味表插入n条数据
        dishFlavorService.saveBatch(flavors);

    }


    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId, d.getId());

            List<DishFlavor> flavors = dishFlavorService.list(wrapper);

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        this.updateById(dish);
    }
}


